package com.he.ucenterservice.service.impl;

import com.alibaba.nacos.client.config.utils.MD5;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.he.baseservice.exceptionhandler.EduException;
import com.he.ucenterservice.entity.RegisterVo;
import com.he.ucenterservice.entity.UcenterMember;
import com.he.ucenterservice.mapper.UcenterMemberMapper;
import com.he.ucenterservice.service.UcenterMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author testhejinyu
 * @since 2021-06-17
 */
@Service
public class UcenterMemberServiceImpl extends ServiceImpl<UcenterMemberMapper, UcenterMember> implements UcenterMemberService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void registerUser(RegisterVo registerVo) {
        // 获得前端传来的数据
        String nickname = registerVo.getNickname();
        String mobile = registerVo.getMobile();
        String password = registerVo.getPassword();
        String code = registerVo.getCode();

        // 校验参数
        if (StringUtils.isEmpty(code) || StringUtils.isEmpty(mobile) ||StringUtils.isEmpty(password) || StringUtils.isEmpty(nickname) ) {
            throw new EduException(20001,"请重新输入规范的信息注册！");
        }

        // 从redis中获取发送的验证码
        String mobileCode = "" + redisTemplate.opsForValue().get(mobile);
        // code是注册输入的验证码，mobileCode是发送短信储存到redis的验证码
        if (!code.equals(mobileCode)) {
            throw new EduException(20001,"注册验证码错误！");
        }
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("mobile",mobile);

        Integer userCount = baseMapper.selectCount(wrapper);
        if( userCount > 0){
            throw new EduException(20001,"此号码已注册！");
        }
        UcenterMember ucenterMember = new UcenterMember();

        ucenterMember.setNickname(nickname);
        ucenterMember.setMobile(mobile);
        ucenterMember.setPassword(MD5.getInstance().getMD5String(password));
        ucenterMember.setIsDeleted(false);

        // 默认头像
        ucenterMember.setAvatar("http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eoj0hHXhgJNOTSOFsS4uZs8x1ConecaVOB8eIl115xmJZcT4oCicvia7wMEufibKtTLqiaJeanU2Lpg3w/132");
        baseMapper.insert(ucenterMember);
    }
}
